<template>
  <a class="back-to-top" @click="toTop" v-if="show">↑</a>
</template>

<script>
export default {
  data() {
    return {
      show: false,
    };
  },
  methods: {
    toTop() {
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });
    },
    handleScroll() {
      const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop; //获取滚动距离
        scrollTop === 0? this.show = false:this.show = true
    },
  },
  mounted() {
    this.$nextTick(function () {
      window.addEventListener("scroll", this.handleScroll);
    });
  },
};
</script>

<style lang="less" scoped>
.back-to-top {
  position: fixed;
  right: 15px;
  bottom: 15px;
  z-index: 998;
  background: #67b0d1;
  width: 40px;
  height: 40px;
  border-radius: 50px;
  transition: all 0.4s;
  color: #fff;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  cursor: pointer;
}
</style>